const resourceModel = require('@/models/resource.model')
const Service = require('./index')
const { transformTree } = require('@/utils/common.util')

class ResourceService extends Service {
  async create (attrs) {
    const { parentId, type, name, code, sort } = attrs
    if (!['menu', 'btn'].includes(type)) {
      return {
        errorMessage: '非法的type值'
      }
    }
    try {
      if (!this.isNull(parentId)) {
        const exist = await resourceModel.exist(parentId)
        if (!exist) {
          return {
            errorMessage: '找不到对应的parentId'
          }
        }
      }
      await resourceModel.create({
        parentId, type, name, code, sort
      })
    } catch (error) {
      throw new Error(error)
    }
  }

  async find (type, searchKeywords) {
    try {
      const data = await resourceModel.find({
        equal: {
          'resource.type': type
        },
        like: {
          'resource.name': searchKeywords
        }
      })
      return transformTree(data, 'id', 'parentId')
    } catch (error) {
      throw new Error(error)
    }
  }

  /**
   * 递归删除资源
   * @param {*} id
   */
  async recursiveDelete (id) {
    try {
      const exist = await resourceModel.exist(id)
      if (!exist) {
        return {
          errorMessage: '资源不存在'
        }
      }
      await resourceModel.delete(id)
    } catch (error) {
      throw new Error(error)
    }
  }

  async update (id, attrs) {
    if (this.isNull(id)) {
      return {
        errorMessage: '缺少必要标识id'
      }
    }
    const { parentId, name, code, type, sort } = attrs
    try {
      const exist = await resourceModel.exist(id)
      if (!exist) {
        return {
          errorMessage: '资源不存在'
        }
      }
      await resourceModel.update(id, {
        parentId, name, code, type, sort
      })
    } catch (error) {
      throw new Error(error)
    }
  }
}

module.exports = new ResourceService()
